﻿
using InstallWizard.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using IWshRuntimeLibrary;//需引用COM组件 Windows Script Host Object Model
using Ionic.Zip;
using Common;

namespace InstallWizard
{
    public partial class Page4 : Form
    {
        AppInfo appInfo = null;
        InstallOptions installOptions = null;
        List<AppFileInfo> fileList = null;
        string pkgFilename = "files.pkg";
        string configFile = "wizard.config";
        string installiniFile = "install.ini";
        string defUnstaller = "Uninstaller.exe";
        
        public Page4()
        {
            InitializeComponent();
        }
        #region 单独不现实窗体关闭按钮
        private const int CP_NOCLOSE_BUTTON = 0x200;
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams myCp = base.CreateParams;
                myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;
                return myCp;
            }
        }
        #endregion
        private void Page4_Load(object sender, EventArgs e)
        {
           
        }
        private void Page4_Shown(object sender, EventArgs e)
        {
            appInfo = DAL.FileIO.ReadConfigFile(configFile, out fileList);
            Text = "正在安装 " + appInfo.GetAppNameVer();
            string user = installOptions.Install4AllUser ? "全部用户" : "当前用户";
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("安装路径：" + installOptions.TargetFolder);
            sb.AppendLine("工作路径：" + installOptions.WorkingFolder);
            sb.AppendLine("为" + user + "创建程序组");
            sb.AppendLine("程序组：" + installOptions.ProgramGroup);
            sb.AppendLine("桌面快捷方式：" + installOptions.DesktopShortcut.ToString());
            txtDesc.Text = sb.ToString();
            picLogo.Load(appInfo.AppLogoFileName);
        }
        public void LoadInstallOptions(InstallOptions installOptions)
        {
            this.installOptions = installOptions;
        }
        private void BtnPrev_Click(object sender, EventArgs e)
        {
            this.Hide();
            Form[] pages = Tag as Form[];
            pages[2].Show();
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void BtnNext_Click(object sender, EventArgs e)
        {//1.解压缩文件包  2. 检查并安装CLR环境   3.生产程序组和快捷方式  4.运行维护程序

            //1. 解压程序文件到指定的目标路径
            try
            {
                using (ZipFile zip = new ZipFile(pkgFilename))
                {
                    zip.ExtractAll(installOptions.TargetFolder,ExtractExistingFileAction.OverwriteSilently);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"解压程序文件时出现错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
            var appFile = fileList.FirstOrDefault(f => f.FileType == EFileType.MainProgram);
            if (appFile == null)
            {
                MessageBox.Show("程序文件清单未包含主程序文件！", "严重错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string afile = Path.Combine(installOptions.TargetFolder, appFile.SourceFile);
            if (!System.IO.File.Exists(afile))
            {
                MessageBox.Show("主程序文件无法找到！", "严重错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //2.检查Net Framework环境
            string[] dotnetVersions = DotnetVersion.GetVersions();
            if (!dotnetVersions.Contains(appInfo.DotnetVersion))
            {
                if (System.IO.File.Exists(appInfo.DotNetFrameworkFile))
                {
                    var result= MessageBox.Show($"需要版本为{appInfo.DotnetVersion}的.NET FRAMEWORK支持。\r\n点击 确定 安装必须的.NET FRAMEWORK环境，或者 取消 安装。", "安装提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    if (result == DialogResult.Cancel) return;
                    Process.Start(appInfo.DotNetFrameworkFile);
                }
                else
                {
                    MessageBox.Show($"需要版本为{appInfo.DotnetVersion}的.NET FRAMEWORK支持，请下载并安装，否则程序将无法运行。","警告",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                }
            }
            ////1 运行需前运行的程序
            //var preRunFile = fileList.FirstOrDefault(f => f.Proceed == EProceed.RunBeforeUpdate);
            //if (preRunFile != null)
            //{
            //    Process.Start(preRunFile.SourceFile);
            //}

            //3. 创建程序组和快捷方式
            //3.1 创建程序组 C:\ProgramData\Microsoft\Windows\Start Menu\Programs
            //C:\ProgramData\Microsoft\Windows\Start Menu\Programs\7-Zip
            var spec1 = Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms);
            //公共程序文件夹
            var spec2 = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory);
            //公共桌面
            var spec3 = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
            //个人程序文件夹
            var spec4 = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //个人桌面
            var spe54 = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            //同上
            
            //找出公共目录
            string pgPath = Path.Combine( spec1, installOptions.ProgramGroup);
            string desktop= Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory);
            string mainApp = Path.Combine(installOptions.TargetFolder, appFile.SourceFile);
            if (!installOptions.Install4AllUser)
            {//个人目录
                pgPath = Path.Combine(spec3, installOptions.ProgramGroup);
                desktop= Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            }

            try
            {
                if (!Directory.Exists(pgPath))
                {
                    Directory.CreateDirectory(pgPath);

                }
                CreateShortCut(pgPath, appInfo.AppName, mainApp, "启动" + appInfo.AppName, installOptions.WorkingFolder, "");
                var file = fileList.FirstOrDefault(f => f.FileType == EFileType.Unistaller);
                if (file != null)
                {//如果有定义卸载器，则创建卸载器快捷方式，如果没有则使用默认的卸载器
                    string uninstFile = Path.Combine(installOptions.TargetFolder, file.SourceFile);
                    CreateShortCut(pgPath, file.SourceFile, uninstFile, "Uninstall", installOptions.TargetFolder, "");
                }
                else if(System.IO.File.Exists(defUnstaller))
                {
                    string fullname = installOptions.TargetFolder + "\\" + defUnstaller;
                    System.IO.File.Copy(defUnstaller, fullname, true);
                    CreateShortCut(pgPath, "Uninstall", fullname, "Uninstall", installOptions.TargetFolder, "-silent");
                }
                file = fileList.FirstOrDefault(f => f.FileType == EFileType.Maintainer);
                if (file != null)
                {//创建程序维护的快捷方式
                    string fullname = Path.Combine(installOptions.TargetFolder, file.SourceFile);
                    CreateShortCut(pgPath, file.SourceFile, fullname, "程序维护", pgPath, "");
                }

                //3.2创建桌面快捷方式
                if (installOptions.DesktopShortcut)
                {
                    CreateShortCut(desktop, appInfo.AppName, mainApp, "启动" + appInfo.AppName, installOptions.WorkingFolder, "");
                }
                #region 保存安装配置
                MyConfiguration opt = new MyConfiguration(false);
                opt.WriteString("TargetFolder", installOptions.TargetFolder);
                opt.WriteString("ProgramGroup", pgPath);
                opt.WriteString("DesktopShortcut", desktop + "\\" + appInfo.AppName + ".lnk");
                opt.Save(installiniFile);
                #endregion
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message,"创建程序组和快捷方式时错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                Process.Start(installOptions.TargetFolder);
            }
           
            //4 运行维护程序
            var postRunFile = fileList.FirstOrDefault(f => f.Proceed == EProceed.RunAfterUpdate);
            if(postRunFile!=null)
            {
                string fullName = Path.Combine(installOptions.TargetFolder, postRunFile.SourceFile);
                try
                {
                    Process.Start(fullName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message,"运行程序出错",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
            }
            MessageBox.Show("安装完毕！OK退出安装程序","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            Application.Exit();
        }

        private void CreateShortCut(string targetPath,string shortcutName,string source,string descript,string workFolder,string arguments)
        {
            WshShell shell = new WshShell();
            IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(targetPath + "\\"+shortcutName+".lnk");
            shortcut.TargetPath = source;
            shortcut.Arguments = arguments;// 参数            
            shortcut.Description = descript;
            shortcut.WorkingDirectory = workFolder;//程序所在文件夹，在快捷方式图标点击右键可以看到此属性            
            shortcut.IconLocation =source+",0";//图标            
                                                                 //shortcut.Hotkey = "CTRL+SHIFT+Z";//热键            
            shortcut.WindowStyle = 1;
            shortcut.Save();
        }
        
      

        private void Page4_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Application.Exit();
        }

       
    }
}
